/*
 * Copyright (C) 2013 The original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy
 * of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

package com.zapta.apps.maniana.model;

import com.zapta.apps.maniana.annotations.ApplicationScope;
import com.zapta.apps.maniana.model.ItemRepeatReadOnly;

/**
 * Represents the data on when an item should repeat
 *
 * @author Elliott Mitchell
 */

@ApplicationScope
public abstract class ItemRepeat implements ItemRepeatReadOnly {
	/** End date for us */
	private int mEndDate;

	ItemRepeat() {
		mEndDate=0;
	}
	ItemRepeat(ItemRepeatReadOnly other) {
		if(other.getType()!=getType()) throw new
RuntimeException("constructing a repeat of one type from a different type");
		mEndDate=other.getEndDate();
	}
	ItemRepeat(ItemModel.StoreIF IF) {
		this.fromStore(IF);
	}

	@Override
	public int getEndDate() {
		return mEndDate;
	}
	public void setEndDate(int endDate) {
		if(endDate==0) mEndDate=-1>>>1;
		else mEndDate = endDate;
	}

	public void toStore(ItemModel.StoreIF IF) {
		if(mEndDate!=-1>>>1) IF.setInt("end_date", mEndDate);
	}

	abstract public void fromStore(ItemModel.StoreIF IF);

	void fromStore(ItemModel.StoreIF IF, final String typestr) {
		if(!IF.getString("repeat_type").contentEquals(typestr)) throw
new RuntimeException("loading a repeat from a store of a different type");

		mEndDate=IF.getInt("end_date");
		if(mEndDate==0) mEndDate=-1>>>1;
	}

	abstract public boolean checkDelete(ItemModel item);
	boolean checkDelete(ItemModel item, int next) {
		if(next<=mEndDate) {
			item.setDueDate(next);
			item.setIsCompleted(false);
			// indicate don't delete us!
			return false;
		// we've hit our end date
		} else return true;
	}
}

